<script setup>

import {ElMessage} from "element-plus";
import {onMounted, ref} from "vue";
import http from "@/request/Http.js";


const userMessage = ref({
  username: '',
  oldPassword: '',
  newPassword: '',
  rePassword: ''
});

const userMessageRef = ref()


const save = async () => {
  //读取userMessage的数据，
  console.log(userMessage.value);
  // 判断旧密码和新密码是否一致，一致则清空表单，并提示
  if (userMessage.value.oldPassword === userMessage.value.newPassword) {
    ElMessage.error("新旧密码相同，修改失败")
    return
  }
  if (userMessage.value.newPassword !== userMessage.value.rePassword) {
    //判断新密码和重复密码是否一致，不一致则提示
    ElMessage.error("新密码和确认密码不一致，修改失败")
    return
  }
  //发送修改请求
  const data = await http.post("/user/changePassword", userMessage.value)
  if (data.code === 200) {
    ElMessage.success("修改成功!")
    //重置表单
    resetPasswordForm()
  } else {
    ElMessage.error("修改失败" + data.msg)
  }
}

// 获取对象信息
const getUserMessage = async () => {
  const data = await http.get("/user/userMessage")
  console.log(data.data.username)
  userMessage.value.username = data.data.username
}

onMounted(async () => {
  await getUserMessage()
})


//重置表单
const resetPasswordForm = () => {
  userMessageRef.value.resetFields()
}

//定义表单校验 规则列表
const rules = {
  //指定一个字段，指定字段的规则
  oldPassword: [
    //非空校验(校验触底规则 触发后的提示信息 触发规则项)
    {required: true, message: "请输入原来密码", trigger: 'blur'},
    //长度校验
    {min: 6, max: 22, message: "长度在6-22个字符之间", trigger: 'blur'}
  ],
  newPassword: [
    //非空校验(校验触底规则 触发后的提示信息 触发规则项)
    {required: true, message: "请输入新密码", trigger: 'blur'},
    //长度校验
    {min: 6, max: 22, message: "密码长度在6-22个字符之间", trigger: 'blur'}
  ],
  rePassword: [
    //非空校验(校验触底规则 触发后的提示信息 触发规则项)
    {required: true, message: "请输入确定密码", trigger: 'blur'},
    //长度校验
    {min: 6, max: 22, message: "密码长度在6-22个字符之间", trigger: 'blur'}
  ]
}
</script>

<template>
  <el-form ref="userMessageRef" :model="userMessage" :rules="rules">
    <el-form-item label="旧密码" prop="oldPassword">
      <!-- show-password 是否显示密码     -->
      <el-input v-model="userMessage.oldPassword" placeholder="请输入原密码" show-password type="password"/>
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model="userMessage.newPassword" placeholder="请输入新密码" show-password type="password"/>
    </el-form-item>
    <el-form-item label="确认密码" prop="rePassword">
      <el-input v-model="userMessage.rePassword" placeholder="请确认密码" show-password type="password"/>
    </el-form-item>
    <!--  保存和关闭按钮-->
    <el-form-item>
      <el-button class="change-button" type="primary" @click="save">保存</el-button>
      <el-button type="warning" @click="resetPasswordForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>

</style>